const { Readable } = require("stream");
const utils = require("../../utils");
const moment = require('moment');
const path = require('path');
const fs = require('fs');
const _ = require('lodash');

module.exports = async function (file, type) {
  const stream = new Readable({ objectMode: true });
  let rowNo = 0, total, rows, func;
  file = path.resolve(process.cwd(), file);
  if (type === 'module') {
    rows = utils.loadModule(file);
  } else {
    if (type === 'function') {
      func = (new Function(`return ${fs.readFileSync(file)}`))();
    } else {
      func = (new Function(`return async ({ _, moment, utils })=>${fs.readFileSync(file)}`))();
    }
    rows = await func({ _, moment, utils });
  }
  total = rows.length;
  stream._read = async function () {
    if (rowNo < total) {
      stream.push(rows[rowNo]);
    } else {
      stream.push(null);
    }
    rowNo++;
  };

  stream.on('end', () => {
    utils.debug('jsonReader [end]');
  });
  
  return stream;
}